package com.aoxon.cargo.adapter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import android.app.Activity;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.Cloth;
import com.aoxon.cargo.database.DataService;
import com.aoxon.cargo.loader.FileLoader;
import com.aoxon.cargo.state.MyStateUtil;
import com.google.gson.Gson;

public class PurGoodsGridAdapter extends BaseAdapter implements MyAdapter {

	private boolean isBusy = false;
	private List<Cloth> cloths;
	private LayoutInflater layoutInflater;
	private HashMap<Cloth, Boolean> state = new HashMap<Cloth, Boolean>();
	DataService dataService;
	
	private boolean isShowCheck = false;
	private FileLoader myImageLoader = new FileLoader(300, 300, true);

	private String tag = "PurGoodsGridAdapter";
	private int width;
	private String deviceId = null;
	
	public PurGoodsGridAdapter(Activity activity, List<Cloth> cloths,
			boolean isShowCheck) {
		this.cloths = cloths;
		this.isShowCheck = isShowCheck;
		dataService = new DataService(activity);
		this.layoutInflater = LayoutInflater.from(activity.getBaseContext());
		try {
			TelephonyManager telMgr = (TelephonyManager) activity.getSystemService(
					activity.TELEPHONY_SERVICE);
			deviceId = telMgr.getDeviceId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕宽度（像素）

	}

	/**
	 * 
	 * @return 是否有删除数据
	 */
	public boolean deleteCheck() {
		boolean ischange = false;
		Log.v("iter", new Gson().toJson(state));
		Iterator<Entry<Cloth, Boolean>> iter = state.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<Cloth, Boolean> entry = iter.next();
			Cloth key = entry.getKey();
			dataService.deleteCollection(deviceId, key.getClothId(), MyStateUtil.COLLECTION_CLOTH);
			cloths.remove(key);
			ischange = true;
		}
		this.notifyDataSetChanged();

		return ischange;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void resetList(List<?> list) {
		// TODO Auto-generated method stub
		if (list != null) {
			this.cloths.clear();
			this.cloths = (List<Cloth>) list;
		}
		this.notifyDataSetChanged();
	}

	@Override
	public void setBusy(boolean isBusy) {
		// TODO Auto-generated method stub
		this.isBusy = isBusy;
	}

	@Override
	public void clearCache() {
		// TODO Auto-generated method stub
		if (myImageLoader != null) {
			myImageLoader.clearCache();
		}
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return cloths.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return cloths.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Log.v(tag, "getView");
		ViewHolder viewHolder = null;

		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = layoutInflater.inflate(R.layout.pur_grid_goods_item,
					null);
			viewHolder.view = (ImageView) convertView
					.findViewById(R.id.ivPurGoodsGridItem);
			viewHolder.pBar = (ProgressBar) convertView
					.findViewById(R.id.pbPurGoodsGridItem);
			viewHolder.cbChoose = (CheckBox) convertView
					.findViewById(R.id.cbPurGoodsGridItem);
			viewHolder.tvGoodsPrice = (TextView) convertView
					.findViewById(R.id.tvGoodsPrice);
			viewHolder.tvGoodsCollectNum = (TextView) convertView
					.findViewById(R.id.tvGoodsCollectNum);
			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewHolder.view
					.getLayoutParams();
			params.height = (int) (width / 2);
			viewHolder.view.setLayoutParams(params);

			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		try {

			final Cloth cloth = cloths.get(position);
			viewHolder.tvGoodsPrice.setText("¥"
					+ cloth.getPrices().get(0).getPrice());
			viewHolder.tvGoodsCollectNum.setText(cloth.getCollectedNum() + "");
			if (isShowCheck) {
				viewHolder.cbChoose.setVisibility(View.VISIBLE);
				viewHolder.cbChoose
						.setChecked(state.get(position) == null ? false : true);
				viewHolder.cbChoose
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {
							@Override
							public void onCheckedChanged(CompoundButton arg0,
									boolean isCheck) {
								// TODO Auto-generated method stub
								if (isCheck) {
									state.put(cloth, isCheck);
								} else {
									state.remove(position);
								}
							}
						});
			}

			String path = "";
			if (cloth.getPictures().size() <= 1) {
				path = cloth.getPictures().get(0).getPictureUrl() + "m.png";
			} else {
				path = cloth.getPictures().get(0).getPictureUrl() + "m.png";
			}

			viewHolder.view.setImageResource(R.drawable.loading);
			if (!isBusy) {
				myImageLoader.displayImage(path, viewHolder.view,
						viewHolder.pBar, false);
			} else {
				myImageLoader.displayImage(path, viewHolder.view,
						viewHolder.pBar, true);
			}

		} catch (Exception e) {
			viewHolder.pBar.setVisibility(View.GONE);
			e.printStackTrace();
		}

		return convertView;
	}

	class ViewHolder {
		ImageView view;
		ProgressBar pBar;
		CheckBox cbChoose;
		TextView tvGoodsPrice;
		TextView tvGoodsCollectNum;
	}

}
